<template>
    <div class="operationBasicsDetail">
        <div class="header">
     
            <van-nav-bar title="编辑品牌" left-text="" left-arrow @click-left="goBack" />
        </div>
        <div class="edit_brand">
            <van-form @submit="onSubmit" validate-first scroll-to-error>
                <van-cell-group inset>
                    <van-field name="brandName" required label="品牌名称" v-model="queryParams.brandName" placeholder="请输入"
                        input-align="right" error-message-align="right" :maxlength="50"
                        :rules="[{ required: true, trigger: 'onBlur', message: '请输入品牌名称' }]" />
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="品牌商标注册证" label="品牌商标注册证" input-align="right" error-message-align="right">
                        <template #input>
                            <UpLoadDom :arr="brandImageList || []" @deleteClick="deleteImg"
                                @postImageClick="postImage('brandImage')" :right="true" :maxCount="1" :isPdfLook="true" />
                        </template>
                    </van-field>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="商标授权使用证明" label="商标授权使用证明" input-align="right" error-message-align="right">
                        <template #input>
                            <UpLoadDom :arr="usageImageList || []" @deleteClick="deleteImg"
                                @postImageClick="postImage('usageImage')" :right="true" :maxCount="1" :isPdfLook="true" />
                        </template>
                    </van-field>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="usages" label="使用授权品类" v-model="queryParams.usages" is-link readonly placeholder="请选择"
                        input-align="right" error-message-align="right" @click="showUsageCategory = true" />
                    <van-popup v-model:show="showUsageCategory" position="bottom">
                        <van-picker :columns="usageCategoryColumns" @confirm="onConfirmUsageCategory"
                            @cancel="showUsageCategory = false">
                            <template #option="option">
                                <div style="width: 100%">
                                    <van-checkbox-group v-model="usages" style="display: inline-block; margin-left: 130px"
                                        ref="usagesRef">
                                        <van-checkbox :name="option.text" shape="square">{{
                                            option.text
                                        }}</van-checkbox>
                                    </van-checkbox-group>
                                </div>
                            </template>
                        </van-picker>
                    </van-popup>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="店铺销售授权" label="店铺销售授权" input-align="right" error-message-align="right">
                        <template #input>
                            <UpLoadDom :arr="sellImageList || []" @deleteClick="deleteImg"
                                @postImageClick="postImage('sellImage')" :right="true" :maxCount="1" :isPdfLook="true" />
                        </template>
                    </van-field>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="sells" label="销售授权品类" v-model="queryParams.sells" is-link readonly placeholder="请选择"
                        input-align="right" error-message-align="right" @click="showSellCategory = true" />
                    <van-popup v-model:show="showSellCategory" position="bottom">
                        <van-picker :columns="sellCategoryColumns" @confirm="onConfirmSellCategory"
                            @cancel="showSellCategory = false">
                            <template #option="option">
                                <div style="width: 100%">
                                    <van-checkbox-group v-model="sells" style="display: inline-block; margin-left: 130px">
                                        <van-checkbox :name="option.text" shape="square">{{
                                            option.text
                                        }}</van-checkbox>
                                    </van-checkbox-group>
                                </div>
                            </template>
                        </van-picker>
                    </van-popup>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="其他补充资质" label="其他补充资质" input-align="right" error-message-align="right">
                        <template #input>
                            <UpLoadDom :arr="otherImageList || []" @deleteClick="deleteImg"
                                @postImageClick="postImage('otherImage')" :right="true" :maxCount="1" :isPdfLook="true" />
                        </template>
                    </van-field>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="联名款/其他授权" label="联名款/其他授权" input-align="right" error-message-align="right">
                        <template #input>
                            <UpLoadDom :arr="jointlyImageList || []" @deleteClick="deleteImg"
                                @postImageClick="postImage('jointlyImage')" :right="true" :maxCount="1" :isPdfLook="true" />
                        </template>
                    </van-field>
                </van-cell-group>
                <div class="addtive_div-btn">
                    <van-button round block  class="addtive_div" :loading="loading"  loading-text="执行中..." type="primary" native-type="submit" v-throttle:click>
                        保存
                    </van-button>
                </div>
            </van-form>
            <van-dialog v-model:show="appShow" title="发起资质审批" :showConfirmButton="false" class="app_pop">
                <van-image :src="colseImg" @click="close"></van-image>
                <div class="content">
                    该供应商此品牌资质目前属于审核不通过状态，请确认是否将本次编辑内容报送品控部~
                </div>
                <div class="button" @click="submitted" v-throttle:click>
                    报送审批
                </div>

            </van-dialog>
        </div>
    </div>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getbrandId, updatebrand } from '@/api/supplierList/index'
import { getDicts } from '@/api/productList/index'
import { getEnvValue } from "@/utils/index";
import { showSuccessToast,showFailToast } from 'vant';
import { loginStore } from "@/store/login";
import { storeToRefs } from "pinia";
import UpLoadDom from '@/components/isImgPdf/upLoadDom.vue'
import { handleImageUpdate } from '@/utils/handleImageUpdate';
const store = loginStore();
const { token } = storeToRefs(store);
const usages = ref<any[]>([]);
const sells = ref<any[]>([])
const showUsageCategory = ref(false)
const usageCategoryColumns = ref([])
const showSellCategory = ref(false)
const sellCategoryColumns = ref([])
const usagesRef = ref()

const route = useRoute()
const router = useRouter()
/** 品牌id */
const uniquekey = computed(() => {
    return route.params.id
})
/** 供应商id */
const supplierId = computed(() => {
    return route.params.supplierId
})
const loading = ref(false)
const queryParams = ref({
    brandName: '',
    brandImage: [],
    usageImage: [],
    usages: '',
    sellImage: [],
    sells: '',
    otherImage: [],
    jointlyImage: []
})
const brandImageList = ref<any[]>([])
const usageImageList = ref<any[]>([])
const sellImageList = ref<any[]>([])
const otherImageList = ref<any[]>([])
const jointlyImageList = ref<any[]>([])

const appShow = ref(false)
const colseImg = new URL("@/assets/approval/close.png", import.meta.url).href;

/** 获取详情 */
const getDetail = async () => {
    const res = await getbrandId(uniquekey.value)

    // 防止后期多个图片 改为数组
    if (res.data.brandImage) {
        brandImageList.value.push({
            url: getEnvValue("VITE_APP_PIC_URL") + res.data.brandImage
        })
    }

    if (res.data.usageImage) {
        usageImageList.value.push({
            url: getEnvValue("VITE_APP_PIC_URL") + res.data.usageImage
        })
    }

    if (res.data.sellImage) {
        sellImageList.value.push({
            url: getEnvValue("VITE_APP_PIC_URL") + res.data.sellImage
        })
    }

    if (res.data.otherImage) {
        otherImageList.value.push({
            url: getEnvValue("VITE_APP_PIC_URL") + res.data.otherImage
        })
    }

    if (res.data.jointlyImage) {
        jointlyImageList.value.push({
            url: getEnvValue("VITE_APP_PIC_URL") + res.data.jointlyImage
        })
    }

    if (res.data.usages) {
        usages.value = res.data.usages.split(',')
    } else {
        usages.value = []
    }
    if (res.data.sells) {
        sells.value = res.data.sells.split(',')
    } else {
        sells.value = []
    }
    queryParams.value = res.data
}
getDetail()

/** 报送审批关闭 */
const close = () => {
    appShow.value = false;
}
/** 报送审批提交 */
const submitted = () => {
    showSuccessToast({ type: "success", message: "报送审批成功" });
    appShow.value = false;
    router.back();
}


/** 使用授权品类 */
const getSupplierType = async () => {
    const res = await getDicts('hm_trademark')
    res.data.forEach(element => {
        element.text = element.dictLabel
        element.value = element.dictValue
    })
    usageCategoryColumns.value = res.data
}
getSupplierType()
/**使用授权品类关闭 */
const onConfirmUsageCategory = () => {
    queryParams.value.usages = usages.value.join(',');
    showUsageCategory.value = false;
}

/** 销售授权品类 */
const getsellCategory = async () => {
    const res = await getDicts('hm_trademark')
    res.data.forEach(element => {
        element.text = element.dictLabel
        element.value = element.dictValue
    })
    sellCategoryColumns.value = res.data
}
getsellCategory()
/**销售授权品类关闭 */
const onConfirmSellCategory = () => {
    queryParams.value.sells = sells.value.join(',')
    showSellCategory.value = false;
}

/**
 * 图片全路径转半路径
 * @param list 
 */
const getPicByfullPath = (list: any[]) => {
    if (list.length > 0) {
        const updatedList = list.map((item: any) => {
            return item.url.split(getEnvValue("VITE_APP_PIC_URL"))[1];
        });
        return updatedList.join(',');
    } else {
        return '';
    }
}

const onSubmit = async () => {
    const list = JSON.parse(JSON.stringify(queryParams.value))
    // 图片转为半路径
    list.brandImage = getPicByfullPath(brandImageList.value)
    list.usageImage = getPicByfullPath(usageImageList.value)
    list.sellImage = getPicByfullPath(sellImageList.value)
    list.otherImage = getPicByfullPath(otherImageList.value)
    list.jointlyImage = getPicByfullPath(jointlyImageList.value)
    list.supplierId = supplierId.value
    loading.value = true
    try{
        await updatebrand(list)
        loading.value = false
        showSuccessToast({ type: 'success', message: '修改品牌成功' });
        router.back()

         // appShow.value = true
    }catch (error) {
        if(error=='timeout'){
      showFailToast('修改品牌失败');
        }
      loading.value = false
    }
}
/** 删除 */
const deleteImg = (list: any, index: number) => {
    list.splice(index, 1);
}
(window as any).msgFromUniapp = function (arg) {
    const imageLists = {
        brandImage: brandImageList.value,
        usageImage: usageImageList.value,
        sellImage: sellImageList.value,
        otherImage: otherImageList.value,
        jointlyImage: jointlyImageList.value,
    };

    const maxCounts = {
        brandImage: 1,
        usageImage: 1,
        sellImage: 1,
        otherImage: 1,
        jointlyImage: 1,
    };

    const imageList = imageLists[arg.name];
    const maxCount = maxCounts[arg.name];

    handleImageUpdate(imageList, arg, maxCount);

}
const postImage = (name: string) => {
    (window as any).uni.webView.postMessage({
        data: {
            type: 'img',
            count: 1,
            name: name,
            url: getEnvValue("VITE_APP_UPLOAD_API") + '/resource/oss/upload',
            header: {
                Authorization: `Bearer ${token.value}`,
                clientid: 'e5cd7e4891bf95d1d19206ce24a7b32e'
            }
        }
    })
}
/** 返回上一页 */
const goBack = () => {
  router.back()
}
</script>
<style lang="less" scoped>
:deep(.van-field__label) {
  width: 120px;
}
.edit_brand {
    background-color: #f6faff;
    width: 100%;
    height: calc(100vh - 90px);
    box-sizing: border-box;
    padding: 10px 15px 94px 15px;
    margin-top: 90px;
    overflow-y: scroll;
}

:deep(.van-form) {
    background-color: #fff;
    // height: 100%;
}

:deep(.van-cell-group--inset) {
    margin: 0 !important;
    border-radius: 0 !important;
}

.app_pop {
    height: 210px !important;
    width: 315px !important;

    .content {
        font-size: 14px;
        color: #000000;
        margin: 20px 0;
    }

    .button {
        background: #0094FF;
        border-radius: 23px;
        font-size: 14px;
        color: #FFFFFF;
        text-align: center;
        height: 36px;
        line-height: 36px;
        margin-bottom: 10px;
    }
}

:deep(.van-dialog__content) {
    padding: 0 16px;
    box-sizing: border-box;

    .van-image {
        position: absolute;
        right: 15px;
        top: 15px;
        width: 10px;
        height: 10px;
    }
}

:deep(.van-field__control) {
    color: #B8BECA !important;
}

:deep(.van-icon-arrow:before) {
    color: #B8BECA !important;
}

:deep(.van-cell) {
    align-items: center;
}
.operationBasicsDetail {
  width: 100%;
  // height: 100vh;
  background: #f6faff;
  box-sizing: border-box;
  display: flex;
  flex-wrap: wrap;
  align-content: space-between;
  justify-content: center;
  align-content: flex-start;

  .header {
    background: linear-gradient(#CDECFF 0%, #FFFFFF 70%);
    filter: blur(0px);
    height: 90px;
    padding-top: 44px;
    box-sizing: border-box;
    width: 100%;
    position: fixed;
    z-index: 6003;

    :deep(.van-icon-arrow-left) {
      color: #1a1b1c !important;
    }

    :deep(.van-nav-bar) {
      background: none !important;
    }

    :deep(.van-nav-bar__content) {
      background-color: transparent !important;
    }
  }

}
:deep(.van-cell-group--inset) {
  margin: 0 !important;
  border-radius: 0 !important;
}

:deep(.van-form) {
  // height: 100%;
  // overflow-y: scroll;
  background-color: #fff;
  // padding-bottom: 35px !important;
}
:deep(.van-field--disabled){
  background-color: #f3f3f3;
  .van-field__control{
    color: #8492AD !important;
    -webkit-text-fill-color:#8492AD !important;
  }
  div[aria-checked=true] .van-radio__icon{
    color: #0094FF !important;
    -webkit-text-fill-color: #0094FF !important;
  }
}
:deep(.van-cell) {
      padding: 20px 15px;
      position: relative;
      &::after{
         content: "";
         display: block;
         height: 2px;
         width: 315px;
         background-color: #F3F3FF;
      }
      
      
  }
  :deep(.van-cell-group):last-child{

      .van-cell{
          border-bottom: none !important;
      }
      
  }
  :deep(.van-field__label) {
    
      color: #464E5D  !important;
  }

  :deep(.van-field__label--required){
      &::before{
          display: none;
      }
      &::after{
          color: var(--van-field-required-mark-color);
          content: "*";
      }
  }
  .imgform{
    :deep(.van-cell) {
        border-bottom: none !important;
        &::after{
            content: none;
        }
    }
  }
.addtive_div-btn {
    position: fixed;
    width: 100%;
    height: 84px;
    bottom: 0;
    left: 0;
    z-index: 110;
    display: flex;
    justify-content: space-between;
    background-color: #fff;
    box-shadow: 0px 0px 8px 0px rgba(189,195,204,0.5);
    box-sizing: border-box;
    padding: 0 15px;
    // padding-bottom: 120px;
    .addtive_div {
        width: 320px;
        height: 44px;
        text-align: center;
        margin: auto;
        //   margin-top: 200px;
       
    }
}
</style>